//
//  CGHomePageViewController.m
//  SchoolClient
//
//  Created by mac on 15/10/27.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "CGHomePageViewController.h"
#import <CoreLocation/CoreLocation.h>

#define SCREEN_WIDTH_SIZE  (([[UIScreen mainScreen] bounds].size.width)/320)
#define SCREEN_HEIGHT_SIZE (([[UIScreen mainScreen].bounds].size.height)/568)
@interface CGHomePageViewController ()<CLLocationManagerDelegate>

@property(nonatomic,strong)UILabel *cityLabel;
//@property(nonatomic,strong)CGSearchBar *searchBar;

@property(nonatomic,strong)UIView *firstLine;
@property(nonatomic,strong)UIView *secondLine;
@property(nonatomic,strong)UIButton *societyButton;          //社会招聘
@property(nonatomic,strong)UIButton *schoolButton;           //校园招聘
@property(nonatomic,strong)NSMutableArray *companyFrames;    //所有企业产品
@property(nonatomic,strong)NSMutableArray *schoolFrames;     //所有学校产品
@property(nonatomic,strong)NSString *model;

@property(nonatomic,strong)CLLocationManager *manager;

@end

@implementation CGHomePageViewController

-(CLLocationManager *)manager{
    if (!_manager) {
        _manager = [[CLLocationManager alloc]init];
        _manager.delegate = self;
        //控制定位服务更新频率为100米(即间隔100米后重新定位)
        _manager.distanceFilter = 100;
        //设置定位精度为千米(精度越小手机越耗电)
        _manager.desiredAccuracy = kCLLocationAccuracyKilometer;
        
        //在ios 8.0下需要授权
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            [_manager requestWhenInUseAuthorization];  //调用了这句话就会弹出允许框了
        }
        //注意：在Info.plist文件还要加上NSLocationWhenInUseUsageDescription这个key,Value可以为空
    }
    return _manager;
}

-(NSMutableArray *)companyFrames{
    if (!_companyFrames) {
        _companyFrames = [NSMutableArray array];
    }
    return _companyFrames;
}

-(NSMutableArray *)schoolFrames{
    if (!_schoolFrames) {
        _schoolFrames = [NSMutableArray array];
    }
    return _schoolFrames;
}

-(NSString *)cityName{
    if (_cityName.length == 0) {
        _cityName  = @"南宁市";
    }
    
    if ([_cityName rangeOfString:@"市"].location != NSNotFound) {
        NSMutableString *mstr = [NSMutableString stringWithString:_cityName];
        NSRange range = NSMakeRange(mstr.length - 1, 1);
        [mstr deleteCharactersInRange:range];
        _cityName = mstr;
    }
    
    return _cityName;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    
    [self initNavigationBarButton];
    [self initCategoryView];
    [self initTableView];
    //默认显示社会招聘信息
    self.model = @"0";
    // 添加下拉刷新控件
    [self.tableView addHeaderWithTarget:self action:@selector(loadNewStatus)];
    
    //  后台执行：
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"%@",[NSThread currentThread]);
        // 自动下拉刷新
        [self.tableView headerBeginRefreshing];
        
    });

    [self addObserver:self forKeyPath:@"cityName" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    

    //上拉加载旧数据
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreStatus)];
    
    //开始定位
    [self.manager startUpdatingLocation];
    
    
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    NSString *newCity = change[@"new"];
    NSString *oldCity = change[@"old"];
    
    if ([newCity isEqualToString:oldCity]) {
        return;
    }
    
    self.cityLabel.text = self.cityName;
    [self.companyFrames removeAllObjects];
    [self.schoolFrames removeAllObjects];
    [self loadNewStatus];
}


#pragma mark 添加导航按钮
-(void)initNavigationBarButton{
    
    //1.设置中间导航视图为searchBar
    /*
    self.searchBar = [[CGSearchBar alloc]initWithFrame:CGRectMake(60, 0, SCREEN_WIDTH - 120, 35)];
    self.searchBar.placeholder = @"查找公司或职位";
    self.navigationItem.titleView = self.searchBar;
    self.searchBar.delegate = self;
    */
    UIButton *searchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 100, 35)];
    [searchButton setBackgroundImage:[UIImage imageNamed:@"login_input_phone_bg"] forState:UIControlStateNormal];
    [searchButton setImage:[UIImage imageNamed:@"navigationbar_search_icon"] forState:UIControlStateNormal];
    [searchButton setTitle:@"  查找公司或职位" forState:UIControlStateNormal];
    [searchButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont systemFontOfSize:14];
    searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    searchButton.imageEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
//    searchButton.titleEdgeInsets = UIEdgeInsetsMake(0, -65 * SCREEN_WIDTH_SIZE, 0, 0);
    
    self.navigationItem.titleView = searchButton;
    
    //添加点击事件
    [searchButton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    //2.左导航按钮
    CGRect btFrame = CGRectMake(-10, 0, 70, 44);
    UIView *leftBarView = [[UIView alloc]initWithFrame:btFrame];
    btFrame.size.width = 60;
    self.cityLabel = [[UILabel alloc]initWithFrame:btFrame];
    self.cityLabel.textColor = [UIColor whiteColor];
    self.cityLabel.font = [UIFont systemFontOfSize:14];
    self.cityLabel.textAlignment = NSTextAlignmentCenter;
    self.cityLabel.adjustsFontSizeToFitWidth = YES;
    
    self.cityLabel.text = self.cityName;
    [leftBarView addSubview:self.cityLabel];
    
    btFrame.origin.x += 60;
    btFrame.origin.y = 20;
    btFrame.size.width = 10;
    btFrame.size.height = 10*12/18;
    
    UIImageView *arrowImageView = [[UIImageView alloc]initWithFrame:btFrame];
    arrowImageView.image = [UIImage imageNamed:@"navigationbar_arrow_down"];
    [leftBarView addSubview:arrowImageView];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBarView];
    //给左导航按钮添加点击事件
    UITapGestureRecognizer *leftTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectedCity:)];
    [leftBarView addGestureRecognizer:leftTap];
    //3.右导航按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"navigationbar_news_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(enterRemindingVC:)];
    
    
}


#pragma mark 添加分类招聘按钮
-(void)initCategoryView{
    
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 43)];
    titleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titleView];
    //社会招聘Button
    CGRect aFrame = CGRectMake(0, 0, SCREEN_WIDTH/2, 43);
    CGRect bFrame = CGRectMake(0, 41, SCREEN_WIDTH/2, 2);
    self.societyButton = [[UIButton alloc]initWithFrame:aFrame];
    [self.societyButton setTitle:@"社会招聘" forState:UIControlStateNormal];
    [self.societyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.societyButton setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    self.societyButton.selected = YES;
    [self.view addSubview:self.societyButton];
    self.firstLine = [[UIView alloc]initWithFrame:bFrame];
    self.firstLine.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.firstLine];
    //添加点击事件
    [self.societyButton addTarget:self action:@selector(categoryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //校园招聘Button
    aFrame.origin.x += SCREEN_WIDTH/2;
    bFrame.origin.x += SCREEN_WIDTH/2;
    self.schoolButton = [[UIButton alloc]initWithFrame:aFrame];
    [self.schoolButton setTitle:@"校园招聘" forState:UIControlStateNormal];
    [self.schoolButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.schoolButton setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [self.view addSubview:self.schoolButton];
    self.secondLine = [[UIView alloc]initWithFrame:bFrame];
    self.secondLine.backgroundColor = [UIColor orangeColor];
    self.secondLine.hidden = YES;
    [self.view addSubview:self.secondLine];
    //添加点击事件
    [self.schoolButton addTarget:self action:@selector(categoryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark 添加表格
-(void)initTableView{
    
    CGRect aRect = CGRectMake(0,44,SCREEN_WIDTH,SCREEN_HEIGHT-64-44-49);
    self.tableView = [[UITableView alloc] initWithFrame:aRect  style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: self.tableView];
}


#pragma mark 下拉刷新
-(void)loadNewStatus{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"pageSize"] =[NSString stringWithFormat:@"%d",(int)SCREEN_HEIGHT/100];
    parameters[@"model"] = self.model;
    parameters[@"city"] = self.cityName;
    
    if ([self.model isEqualToString:@"0"]) {
        if (!self.companyFrames.count) {
            parameters[@"page"] = @"0";   //第一次加载最新的数据
        }else{
            CGInfoCompanyFrame *companyFrame = [self.companyFrames firstObject];
            parameters[@"uid"] = [NSString stringWithFormat:@"%d",companyFrame.product.uid];
        }
        
    }else{
        if (!self.schoolFrames.count) {
            parameters[@"page"] = @"0";   //第一次加载最新的数据
        }else{
            CGInfoSchoolFrame *schoolFrame = [self.schoolFrames firstObject];
            parameters[@"uid"] = [NSString stringWithFormat:@"%d",schoolFrame.product.uid];
        }
    }
    
    //检查网络是否可用
    if (![ZYHRequest NetWorkIsOK]) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络不可用"];
        // 结束下拉刷新
        [self.tableView headerEndRefreshing];
        return;
    }
    
    ZYHRequest *request = [ZYHRequest new];

    [request postAsyncEncryptRequest:@"/main/getHomeData.app" parameters:parameters success:^(id responseData) {
   
        NSLog(@"招聘信息刷新请求成功!!");
        // 结束下拉刷新
        [self.tableView headerEndRefreshing];
        //把接收到的数组对象变成model
        NSDictionary *jsonDic =  [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:NULL];
        NSString *value = jsonDic[@"data"];
        if (value.length == 0) {
            return ;
        }
        NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"result:%@",value);
       
        if ([self.model isEqualToString:@"0"]) {
            
            NSArray *companyArr = [CGInfoCompany objectArrayWithJSONData:valueData];
            //把模型转成视图模型
            NSMutableArray *companyFrameArr = [NSMutableArray array];
            for (CGInfoCompany *company in companyArr) {
                CGInfoCompanyFrame *companyFrame = [CGInfoCompanyFrame new];
                companyFrame.product = company;
                [companyFrameArr addObject:companyFrame];
            }
            
            // 把最新的招聘信息插入到最前面
            NSIndexSet *comIndex = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, companyArr.count)];
            [self.companyFrames insertObjects:companyFrameArr atIndexes:comIndex];
            
        }else{
            
            NSArray *schoolArr = [CGInfoSchool objectArrayWithJSONData:valueData];
            //把模型转成视图模型
            NSMutableArray *schoolFrameArr = [NSMutableArray array];
            for (CGInfoSchool *school in schoolArr) {
                CGInfoSchoolFrame *schoolFrame = [CGInfoSchoolFrame new];
                schoolFrame.product = school;
                [schoolFrameArr addObject:schoolFrame];
            }
            
            // 把最新的招聘信息插入到最前面
            NSIndexSet *schIndex = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, schoolArr.count)];
            [self.schoolFrames insertObjects:schoolFrameArr atIndexes:schIndex];
        }
    
        // 刷新表格
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
        NSLog(@"招聘信息刷新请求失败:%@",error);
    }];
    
}



#pragma mark 上拉加载
-(void)loadMoreStatus{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"model"] = self.model;
    parameters[@"pageSize"] =[NSString stringWithFormat:@"%d",(int)SCREEN_HEIGHT/100];
    parameters[@"city"] = self.cityName;
    
    if ([self.model isEqualToString:@"0"]) {
        if (!self.companyFrames.count) {
            // 结束上拉加载
            [self.tableView footerEndRefreshing];
            return;                   //有数据才需要加载
        }else{
            parameters[@"page"] = [NSString stringWithFormat:@"%lu",(unsigned long)self.companyFrames.count];
        }
        
    }else{
        if (!self.schoolFrames.count) {
            // 结束上拉加载
            [self.tableView footerEndRefreshing];
            return;                     //有数据才需要加载
        }else{
            parameters[@"page"] = [NSString stringWithFormat:@"%lu",(unsigned long)self.schoolFrames.count];
        }
    }
    
    //检查网络是否可用
    if (![ZYHRequest NetWorkIsOK]) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络不可用"];
        // 结束上拉加载
        [self.tableView footerEndRefreshing];
        return;
    }

    ZYHRequest *request = [ZYHRequest new];
    
    [request postAsyncEncryptRequest:@"/main/getHomeData.app" parameters:parameters success:^(id responseData) {
        
        NSLog(@"招聘信息加载请求成功!!");
        // 结束上拉加载
        [self.tableView footerEndRefreshing];
        
        //把接收到的数组对象变成model
        NSDictionary *jsonDic =  [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:NULL];
        NSString *value = jsonDic[@"data"];
        if (value.length == 0) {
            return ;
        }
        NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
//        NSArray *dicArray = [NSArray array];
        
        if ([self.model isEqualToString:@"0"]) {
            NSArray *dicArray = [CGInfoCompany objectArrayWithJSONData:valueData];
            //把模型转成视图模型
            NSMutableArray *companyFrameArr = [NSMutableArray array];
            for (CGInfoCompany *company in dicArray) {
                CGInfoCompanyFrame *companyFrame = [CGInfoCompanyFrame new];
                companyFrame.product = company;
                [companyFrameArr addObject:companyFrame];
            }
 
            //把数组中的元素添加进去
            [self.companyFrames addObjectsFromArray:companyFrameArr];
            
        }else{
            
            NSArray *dicArray = [CGInfoSchool objectArrayWithJSONData:valueData];
            //把模型转成视图模型
            NSMutableArray *schoolFrameArr = [NSMutableArray array];
            for (CGInfoSchool *school in dicArray) {
                CGInfoSchoolFrame *schoolFrame = [CGInfoSchoolFrame new];
                schoolFrame.product = school;
                [schoolFrameArr addObject:schoolFrame];
            }
            
            //把数组中的元素添加进去
            [self.schoolFrames addObjectsFromArray:schoolFrameArr];
        }

        // 刷新表格
        [self.tableView reloadData];
        
        
    } failure:^(NSError *error) {
        
        NSLog(@"招聘信息加载请求失败:%@",error);
    }];

}



#pragma mark 分类按钮点击事件
-(void)categoryButtonClick:(UIButton *)sender{
    
    if (sender == self.societyButton) {
        NSLog(@"选中了社会招聘");
        self.societyButton.selected = YES;
        self.schoolButton.selected = NO;
        self.firstLine.hidden = NO;
        self.secondLine.hidden = YES;
        self.model = @"0";
        
    }else{
        NSLog(@"选中了校园招聘");
        self.societyButton.selected = NO;
        self.schoolButton.selected = YES;
        self.firstLine.hidden = YES;
        self.secondLine.hidden = NO;
        self.model = @"1";
    }
    
    [self loadNewStatus];
}

#pragma mark 导航按钮点击事件
//城市选择事件
-(void)selectedCity:(UITapGestureRecognizer *)gr{
    
        CGProvinceViewController *provinceVC = [CGProvinceViewController new];
        provinceVC.cityName = self.cityName;
        provinceVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:provinceVC animated:YES];

}

//点击搜索框进入搜索界面
-(void)searchButtonClick{
    
    CGSearchViewController *searchView = [CGSearchViewController new];
    searchView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchView animated:NO];
    
}

#pragma mark 右导航按钮点击事件
-(void)enterRemindingVC:(UIBarButtonItem *)sender{

    CGRemindingViewController *remindingVC = [CGRemindingViewController new];
    remindingVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:remindingVC animated:YES];
}


#pragma mark overide 表格的代理方法实现
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ([self.model isEqualToString:@"0"]) {
        
        return self.companyFrames.count;
        
    }else{
        
        return self.schoolFrames.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.model isEqualToString:@"0"]) {
        
        CGCompanyJobCell *cell = [tableView dequeueReusableCellWithIdentifier:@"company"];
        if (cell == nil) {
            cell = [[CGCompanyJobCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"company"];
        }
        cell.productFrame = self.companyFrames[indexPath.row];
        return cell;
        
    }else{
        
        CGSChoolJobCell *cell = [tableView dequeueReusableCellWithIdentifier:@"school"];
        if (cell == nil) {
            cell = [[CGSChoolJobCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"school"];
        }
        
        cell.productFrame = self.schoolFrames[indexPath.row];
        return cell;
    }
}

#pragma mark 选中职位跳转到详情页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([self.model isEqualToString:@"0"]) {
        
        CGInfoCompanyFrame *myCompanyFrame = self.companyFrames[indexPath.row];
        CGCompanyJobDetailViewController *companyDetailVC = [CGCompanyJobDetailViewController new];
        companyDetailVC.myCompanyInfo = myCompanyFrame.product;
        companyDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:companyDetailVC animated:YES];
        
    }else{
        
        CGInfoSchoolFrame *mySchoolFrame = self.schoolFrames[indexPath.row];
        CGSchoolJobDetailViewController *schoolDetailVC = [CGSchoolJobDetailViewController new];
        schoolDetailVC.mySchoolInfo = mySchoolFrame.product;
        schoolDetailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:schoolDetailVC animated:YES];
    }
}


//设置单元格高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.model isEqualToString:@"0"]) {
        

        CGInfoCompanyFrame *companyFrame = self.companyFrames[indexPath.row];
        return companyFrame.cellHeight;
        
    }else{
        
        CGInfoSchoolFrame *schoolFrame = self.schoolFrames[indexPath.row];
        return schoolFrame.cellHeight;
    }

}


//定位到用户位置会调用该方法(并且该方法会调用非常频繁)
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
     NSLog(@"定位到用户位置");
    //获取用户定位的对象
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"纬度：%.2f 经度：%.2f",coordinate.latitude,coordinate.longitude);
    //停止定位(如果不停止，会一直执行非常耗电)
    [manager stopUpdatingLocation];
    //开始反地理编码
    [self reverseGeocodeWithLocation:location];
}

//反地理编码获取当前城市名称
-(void)reverseGeocodeWithLocation:(CLLocation *)location{
    
    if (location == nil) return;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count == 0 || error) return ;
        
        CGDataCenter *dataCenter = [CGDataCenter sharedDataCenter];
        CLPlacemark *placemark = [placemarks firstObject];
        
        if (placemark.locality) {
            self.cityName = placemark.locality;
            dataCenter.selectedCity = placemark.locality;
            
        }else{   //直辖市
            self.cityName = placemark.administrativeArea;
            dataCenter.selectedCity = placemark.administrativeArea;
        }
        self.cityLabel.text = self.cityName;
    
    }];
}


//UITableViewCell左侧会有默认15像素的空白,使cell的线条充满
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
}

@end


